package com.fu.shop.controller;

import com.fu.core.common.BusinessException;
import com.fu.core.common.JsonResult;
import com.fu.core.pojo.OrderDetailsVo;
import com.fu.shop.service.OrderService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @author 付龙江
 * @date 2022/1/28 23:39
 */
@RestController
@CrossOrigin
@RequestMapping("/orderManager")
@Api(tags = "后台订单管理")
public class OrderController {


    OrderService orderService;

    @Autowired
    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }

    @PostMapping(value = "/orderList")
    @ApiOperation(value = "订单管理")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "size", value = "每页条数", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "name", value = "订单号或用户名", dataType = "String", required = false),
            @ApiImplicitParam(name = "from", value = "开始时间", dataType = "String", required = false),
            @ApiImplicitParam(name = "to", value = "结束时间（要比开始时间大）", dataType = "String", required = false),
            @ApiImplicitParam(name = "successStatus", value = "已完成（选中是1 没选中是0或null）", dataType = "Integer", required = false),
            @ApiImplicitParam(name = "notPay", value = "待付款（选中是1 没选中是0或null）", dataType = "Integer", required = false),
            @ApiImplicitParam(name = "distribution", value = "配送中（选中是1 没选中是0或null）", dataType = "Integer", required = false),
            @ApiImplicitParam(name = "failedStatus", value = "已取消（选中是1 没选中是0或null）", dataType = "Integer", required = false)
    })
    public Map<String,Object> orderList(String from,String to, Integer successStatus,Integer notPay,
                                       Integer distribution, Integer failedStatus, String name,
                                       Integer page, Integer size){

        PageInfo<Map<String, Object>> mapPageInfo = orderService.selectOrderList(from, to, successStatus, notPay, distribution, failedStatus, name, page, size);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setField("total",mapPageInfo.getTotal());
        jsonResult.setField("orderList",mapPageInfo.getList());
        return jsonResult.getMap();
    }

    @PostMapping("/uploadOrderList")
    @ApiOperation(value = "导出订单信息")
    public void uploadOrderList(HttpServletResponse response)throws IOException {
        List<Map<String, Object>> list = orderService.uploadOrderList();
        //导出
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("订单信息表");
        String fileName="订单信息表"+".xls";
        fileName = URLEncoder.encode(fileName, "utf-8").replaceAll("\\+", "%20");
        String[] headers = {"ID", "订单编号", "用户姓名", "商品数量", "实付金额","订单状态", "下单时间"};
        // 创建一个行对象, 作为表头
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            // 在行中添加单元格
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            // 把字段名添加到表头行上
            cell.setCellValue(text);
        }
        int rowNum = 1;
        for (Map<String, Object> map : list) {
            HSSFRow dataRow = sheet.createRow(rowNum);
            dataRow.createCell(0).setCellValue(map.get("orderId").toString());
            dataRow.createCell(1).setCellValue(map.get("orderNum").toString());
            dataRow.createCell(2).setCellValue(map.get("userName").toString());
            dataRow.createCell(3).setCellValue(map.get("goodsNum").toString());
            dataRow.createCell(4).setCellValue(map.get("actuallyPaid").toString());
            dataRow.createCell(5).setCellValue(map.get("orderStatus").toString());
            dataRow.createCell(6).setCellValue(map.get("orderTime").toString());
            rowNum++;
        }
        //返回给前端下载
        response.setContentType("application/octet-stream");
        //附件格式打卡，不是打开页面
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }



    @PostMapping(value = "/orderDetails")
    @ApiOperation(value = "订单详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单id，切记是id号  而不是订单编号", dataType = "Integer", required = true)
    })
    public Map<String,Object> orderDetail(Integer orderId) throws BusinessException {
        OrderDetailsVo orderDetailsVo = orderService.selectOrderDetails(orderId);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setField("orderDetails",orderDetailsVo);
        jsonResult.setMsg("成功 ");
        return jsonResult.getMap();
    }

    @PostMapping(value = "/cancelOrder")
    @ApiOperation(value = "取消订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单id，切记是id号  而不是订单编号", dataType = "Integer", required = true)
    })
    public Map<String,Object> cancelOrder(Integer orderId) throws Exception {
        orderService.cancelOrder(orderId);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("取消成功 ");
        return jsonResult.getMap();
    }

}
